package com.kws.tool.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.core.utils.StringUtils;
import com.kws.tool.dto.ElectricityPriceByCIdDto;
import com.kws.tool.dto.ElectricityPriceDto;
import com.kws.tool.entity.*;
import com.kws.tool.mapper.ElectricityTypeIMapper;
import com.kws.tool.mapper.PhotovoltaicMapper;
import com.kws.tool.service.*;
import com.kws.tool.util.InitHashMapUtil;
import com.kws.tool.util.SignUtils;
import com.kws.tool.util.TemplateService;
import com.kws.tool.util.Constant;
import com.kws.tool.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : zhangbenting
 * @date : 2024/10/23 16:44
 * @Version: 1.0
 */
@Service
@Slf4j
public class PhotovoltaicServiceImpl extends ServiceImpl<PhotovoltaicMapper, PhotovoltaicEntity> implements PhotovoltaicService {

    @Autowired
    private TemplateService templateService;

    @Autowired
    private ElectricityTypeIService electricityTypeIService;

    @Autowired
    private ElectricityTypeIMapper electricityTypeIMapper;

    @Autowired
    private ElectricityTypeTwoVoltageService electricityTypeTwoVoltageService;

    @Autowired
    private ElectricityMonthChooseService electricityMonthChooseService;

    @Autowired
    private ElectricityDivideHourService electricityDivideHourService;

    @Autowired
    private ElectricityDivideMonthService electricityDivideMonthService;

    @Autowired
    private ElectricityLevelService electricityLevelService;

    @Autowired
    private ElectricityMonthChooseAnalysisService electricityMonthChooseAnalysisService;

    @Autowired
    private ElectricityPeakValleySpreadService electricityPeakValleySpreadService;

    @Autowired
    private ElectricityPriceAnalysisService electricityPriceAnalysisService;

    @Autowired
    private ElectricityPriceDifferenceService electricityPriceDifferenceService;

    @Autowired
    private ElectricityPriceCidService electricityPriceCidService;

    @Value("${prosperity.appId}")
    public String appId;
    @Value("${prosperity.appSecret}")
    public String appSecret;

    @Override
    public List<RegionVo> getRegionAndElectricityTypeI(ElectricityPriceDto electricityPriceDto) {
        List<RegionVo> regionVoList = new ArrayList<>();
        JSONObject jsonObject = getRegionAndElectricityTypeIData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                regionVoList = JSON.parseArray(JSON.toJSONString(dataList), RegionVo.class);
            }
            return regionVoList;
        } else {
            //此处为获取不到第三方数据，则使用库里的数据
            return getRegionAndElectricityTypeIStatic(electricityPriceDto);
        }
    }

    public JSONObject getRegionAndElectricityTypeIData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        String url = Constant.DQ_YDLXI;
        if (StringUtils.isNotEmpty(electricityPriceDto.getType())) {
            url = url + "?type=" + electricityPriceDto.getType();
        }
        //请求第三方接口
        Object dataObject = templateService.get(url, headerMap, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateRegionAndElectricityTypeIData() {
        ElectricityPriceDto electricityPriceDto = new ElectricityPriceDto();
        electricityPriceDto.setType("all");

        // 获取数据
        JSONObject jsonObject = getRegionAndElectricityTypeIData(electricityPriceDto);

        // 判断响应码是否正确
        if (!Integer.valueOf(0).equals(jsonObject.getInteger("resp_code"))) {
            log.info("采集数据失败-获取地区和用电类型I: {}", jsonObject.toJSONString());
            return false;
        }

        // 获取数据列表
        JSONArray dataList = jsonObject.getJSONArray("datas");
        if (dataList == null || dataList.isEmpty()) {
            log.info("采集数据为空-获取地区和用电类型I");
            return false;
        }

        // 将 JSONArray 转换为 List<RegionVo>
        List<RegionVo> regionVoList = JSON.parseArray(JSON.toJSONString(dataList), RegionVo.class);

        // 转换为数据库实体列表
        List<ElectricityTypeOneEntity> electricityTypeIEntities = regionVoList.stream()
                .flatMap(regionVo -> regionVo.getReInvestmentElectricityType().stream()
                        .map(reInvestmentElectricityType -> {
                            ElectricityTypeOneEntity entity = new ElectricityTypeOneEntity();
                            entity.setRegionName(regionVo.getRegionName());
                            entity.setOneParamDesc(reInvestmentElectricityType.getParamDesc());
                            entity.setOneParamName(reInvestmentElectricityType.getParamName());
                            return entity;
                        }))
                .collect(Collectors.toList());
        // 全量更新：先删除旧数据，再批量保存新数据
        electricityTypeIMapper.deleteAllElectricityTypes();
        return electricityTypeIService.saveOrUpdateBatch(electricityTypeIEntities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateVoltageAndElectricityTypeII() {
        LambdaQueryWrapper<ElectricityTypeOneEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.ne(ElectricityTypeOneEntity::getRegionName, "全国");
        List<ElectricityTypeOneEntity> list = electricityTypeIService.list(wrapper);

        if (list == null || list.size() > 0) {
            List<ElectricityTypeTwoVoltageEntity> voltageEntityArrayList = new ArrayList<>();

            for (ElectricityTypeOneEntity typeOneEntity : list) {
                ElectricityPriceDto dto = new ElectricityPriceDto();
                dto.setElectricityTypeOneName(typeOneEntity.getOneParamName());
                dto.setRegionName(typeOneEntity.getRegionName());

                // 调取第三方接口
                JSONObject jsonObject = getVoltageAndElectricityTypeIIData(dto);

                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(jsonObject.getInteger("resp_code"))) {
                    log.info("采集数据失败-获取电压等级和用电类型II: {}", jsonObject.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = jsonObject.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-获取电压等级和用电类型II");
                    return false;
                }

                List<VoltageVo> voltageVos = JSON.parseArray(JSON.toJSONString(dataList), VoltageVo.class);
                for (VoltageVo voltageVo : voltageVos) {
                    for (VoltageVo.VoltageLevel voltageLevel : voltageVo.getVoltageLevel()) {
                        ElectricityTypeTwoVoltageEntity electricityTypeTwoVoltageEntity = new ElectricityTypeTwoVoltageEntity();
                        electricityTypeTwoVoltageEntity.setOneParamName(typeOneEntity.getOneParamName());
                        electricityTypeTwoVoltageEntity.setRegionName(typeOneEntity.getRegionName());
                        electricityTypeTwoVoltageEntity.setTwoParamName(voltageVo.getParamName());
                        electricityTypeTwoVoltageEntity.setTwoParamDesc(voltageVo.getParamDesc());
                        electricityTypeTwoVoltageEntity.setVoltageParamName(voltageLevel.getParamName());
                        electricityTypeTwoVoltageEntity.setVoltageParamDesc(voltageLevel.getParamDesc());
                        voltageEntityArrayList.add(electricityTypeTwoVoltageEntity);
                    }
                }

                // 控制请求频率：每次请求后暂停一段时间
                try {
                    Thread.sleep(1000); // 每 1000 毫秒发一次请求（1 次/秒）
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }

            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityTypesVoltage();
            return electricityTypeTwoVoltageService.saveOrUpdateBatch(voltageEntityArrayList);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean updateMonthChoose() {
        List<ElectricityTypeTwoVoltageEntity> list = electricityTypeTwoVoltageService.list();
        if (list != null && list.size() > 0) {
            ElectricityPriceDto dto = new ElectricityPriceDto();
            List<ElectricityMonthChooseEntity> electricityMonthChooseEntities = new ArrayList<>();
            for (ElectricityTypeTwoVoltageEntity twoVoltageEntity : list) {
                dto.setElectricityTypeOneName(twoVoltageEntity.getOneParamName());
                dto.setElectricityTypeTwoName(twoVoltageEntity.getTwoParamName());
                dto.setTariffLevelId(twoVoltageEntity.getVoltageParamName());
                dto.setRegionName(twoVoltageEntity.getRegionName());
                //获取第三方数据
                JSONObject monthChooseData = getMonthChooseData(dto);
                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(monthChooseData.getInteger("resp_code"))) {
                    log.info("采集数据失败-月份选择: {}", monthChooseData.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = monthChooseData.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-月份选择");
                    return false;
                }
                List<MonthChooseVo> monthChooseVos = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
                // 循环添加数据
                for (MonthChooseVo monthChooseVo : monthChooseVos) {
                    ElectricityMonthChooseEntity electricityMonthChoose = new ElectricityMonthChooseEntity();
                    electricityMonthChoose.setOneParamName(twoVoltageEntity.getOneParamName());
                    electricityMonthChoose.setTwoParamName(twoVoltageEntity.getTwoParamName());
                    electricityMonthChoose.setVoltageParamName(twoVoltageEntity.getTwoParamName());
                    electricityMonthChoose.setRegionName(twoVoltageEntity.getRegionName());
                    electricityMonthChoose.setMonthParamDesc(monthChooseVo.getParamDesc());
                    electricityMonthChoose.setMonthParamName(monthChooseVo.getParamName());
                    electricityMonthChooseEntities.add(electricityMonthChoose);
                }
                // 控制请求频率：每次请求后暂停一段时间
                try {
                    Thread.sleep(125); // 每 125 毫秒发一次请求（8 次/秒）
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityMonthChoose();

            return electricityMonthChooseService.saveOrUpdateBatch(electricityMonthChooseEntities);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDivideHourElectricity() {
        List<ElectricityMonthChooseEntity> list = electricityMonthChooseService.list();
        if (list != null && list.size() > 0) {
            ElectricityPriceDto dto = new ElectricityPriceDto();
            List<ElectricityDivideHourEntity> electricityDivideHourEntities = new ArrayList<>();
            for (ElectricityMonthChooseEntity electricityMonthChooseEntity : list) {
                String oneParamName = electricityMonthChooseEntity.getOneParamName();
                String twoParamName = electricityMonthChooseEntity.getTwoParamName();
                String voltageParamName = electricityMonthChooseEntity.getVoltageParamName();
                String regionName = electricityMonthChooseEntity.getRegionName();
                String monthParamName = electricityMonthChooseEntity.getMonthParamName();
                dto.setElectricityTypeOneName(oneParamName);
                dto.setElectricityTypeTwoName(twoParamName);
                dto.setTariffLevelId(voltageParamName);
                dto.setRegionName(regionName);
                dto.setYears(monthParamName);
                JSONObject jsonObject = getDivideHourElectricityData(dto);
                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(jsonObject.getInteger("resp_code"))) {
                    log.info("采集数据失败-获取分时电价图表: {}", jsonObject.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = jsonObject.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-获取分时电价图表");
                    return false;
                }
                List<DivideHourVo> divideHourVos = JSON.parseArray(JSON.toJSONString(dataList), DivideHourVo.class);
                for (DivideHourVo divideHourVo : divideHourVos) {
                    ElectricityDivideHourEntity divideHourEntity = new ElectricityDivideHourEntity();
                    divideHourEntity.setOneParamName(oneParamName);
                    divideHourEntity.setTwoParamName(twoParamName);
                    divideHourEntity.setVoltageParamName(voltageParamName);
                    divideHourEntity.setRegionName(regionName);
                    divideHourEntity.setMonthParamName(monthParamName);
                    divideHourEntity.setStartTime(divideHourVo.getStartTime());
                    divideHourEntity.setEndTime(divideHourVo.getEndTime());
                    divideHourEntity.setPeriodType(divideHourVo.getPeriodType());
                    divideHourEntity.setElectrovalence(divideHourVo.getElectrovalence());
                    electricityDivideHourEntities.add(divideHourEntity);
                }
                // 控制请求频率：每次请求后暂停一段时间
                try {
                    Thread.sleep(1000); // 每 1000 毫秒发一次请求（1 次/秒）
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityDivideHour();

            return electricityDivideHourService.saveOrUpdateBatch(electricityDivideHourEntities);

        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDivideMonthElectricity() {
        List<ElectricityTypeTwoVoltageEntity> list = electricityTypeTwoVoltageService.list();
        if (list != null && list.size() > 0) {
            ElectricityPriceDto dto = new ElectricityPriceDto();
            List<ElectricityDivideMonthEntity> electricityDivideMonthEntities = new ArrayList<>();
            for (ElectricityTypeTwoVoltageEntity twoVoltageEntity : list) {
                dto.setElectricityTypeOneName(twoVoltageEntity.getOneParamName());
                dto.setElectricityTypeTwoName(twoVoltageEntity.getTwoParamName());
                dto.setTariffLevelId(twoVoltageEntity.getVoltageParamName());
                dto.setRegionName(twoVoltageEntity.getRegionName());
                //获取第三方数据
                JSONObject divideMonthElectricityData = getDivideMonthElectricityData(dto);
                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(divideMonthElectricityData.getInteger("resp_code"))) {
                    log.info("采集数据失败-月份选择: {}", divideMonthElectricityData.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = divideMonthElectricityData.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-月份选择");
                    return false;
                }
                List<DivideMonthVo> divideMonthVoList = JSON.parseArray(JSON.toJSONString(dataList), DivideMonthVo.class);
                // 循环添加数据
                for (DivideMonthVo divideMonthVo : divideMonthVoList) {
                    DivideMonthVo.DivideMonth data = divideMonthVo.getData();
                    ElectricityDivideMonthEntity electricityDivideMonth = new ElectricityDivideMonthEntity();
                    electricityDivideMonth.setMonth(divideMonthVo.getMonth());
                    electricityDivideMonth.setOneParamName(twoVoltageEntity.getOneParamName());
                    electricityDivideMonth.setTwoParamName(twoVoltageEntity.getTwoParamName());
                    electricityDivideMonth.setVoltageParamName(twoVoltageEntity.getVoltageParamName());
                    electricityDivideMonth.setRegionName(twoVoltageEntity.getRegionName());
                    electricityDivideMonth.setTopTime(data.getTopTime());
                    electricityDivideMonth.setHighTime(data.getHighTime());
                    electricityDivideMonth.setLowTime(data.getLowTime());
                    electricityDivideMonth.setFlatTime(data.getFlatTime());
                    electricityDivideMonth.setDeepTime(data.getDeepTime());
                    electricityDivideMonthEntities.add(electricityDivideMonth);
                }
                // 控制请求频率：每次请求后暂停一段时间
                try {
                    Thread.sleep(1000); // 每 125 毫秒发一次请求（8 次/秒）
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityDivideMonth();

            return electricityDivideMonthService.saveOrUpdateBatch(electricityDivideMonthEntities);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePeakValleyPriceDifference() {
        List<ElectricityTypeTwoVoltageEntity> list = electricityTypeTwoVoltageService.list();
        if (list != null && list.size() > 0) {
            ElectricityPriceDto dto = new ElectricityPriceDto();
            List<ElectricityPriceDifferenceEntity> electricityPriceDifferenceEntities = new ArrayList<>();
            for (ElectricityTypeTwoVoltageEntity twoVoltageEntity : list) {
                dto.setElectricityTypeOneName(twoVoltageEntity.getOneParamName());
                dto.setElectricityTypeTwoName(twoVoltageEntity.getTwoParamName());
                dto.setTariffLevelId(twoVoltageEntity.getVoltageParamName());
                dto.setRegionName(twoVoltageEntity.getRegionName());
                //获取第三方数据
                JSONObject differenceData = getPeakValleyPriceDifferenceData(dto);
                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(differenceData.getInteger("resp_code"))) {
                    log.info("采集数据失败-峰谷差价图: {}", differenceData.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = differenceData.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-峰谷差价图");
                    return false;
                }
                List<PeakValleyVo> peakValleyVoList = JSON.parseArray(JSON.toJSONString(dataList), PeakValleyVo.class);
                // 循环添加数据
                for (PeakValleyVo peakValleyVo : peakValleyVoList) {
                    PeakValleyVo.PeakValley data = peakValleyVo.getData();
                    ElectricityPriceDifferenceEntity electricityPriceDifference = new ElectricityPriceDifferenceEntity();
                    electricityPriceDifference.setMonth(peakValleyVo.getMonth());
                    electricityPriceDifference.setOneParamName(twoVoltageEntity.getOneParamName());
                    electricityPriceDifference.setTwoParamName(twoVoltageEntity.getTwoParamName());
                    electricityPriceDifference.setVoltageParamName(twoVoltageEntity.getVoltageParamName());
                    electricityPriceDifference.setRegionName(twoVoltageEntity.getRegionName());
                    electricityPriceDifference.setHeightDifference(data.getHeightDifference());
                    electricityPriceDifference.setSharpDifference(data.getSharpDifference());
                    electricityPriceDifference.setAltitudeBalance(data.getAltitudeBalance());
                    electricityPriceDifference.setSharpAdjustment(data.getSharpAdjustment());
                    electricityPriceDifferenceEntities.add(electricityPriceDifference);
                }
                // 控制请求频率：每次请求后暂停一段时间
                try {
                    Thread.sleep(1000); // 每 125 毫秒发一次请求（8 次/秒）
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityPriceDifference();

            return electricityPriceDifferenceService.saveOrUpdateBatch(electricityPriceDifferenceEntities);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateElectricityLevel() {
        List<ElectricityTypeOneEntity> list = electricityTypeIService.list();
        if (list != null && list.size() > 0) {
            List<String> oneTypeList = list.stream().map(ElectricityTypeOneEntity::getOneParamName).distinct().collect(Collectors.toList());
            ElectricityPriceDto dto = new ElectricityPriceDto();
            List<ElectricityLevelEntity> electricityLevelEntities = new ArrayList<>();
            for (String oneType : oneTypeList) {
                dto.setElectricityTypeOneName(oneType);
                JSONObject electricityLevelData = getElectricityLevelData(dto);
                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(electricityLevelData.getInteger("resp_code"))) {
                    log.info("采集数据失败-电压等级: {}", electricityLevelData.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = electricityLevelData.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-电压等级");
                    return false;
                }
                List<MonthChooseVo> monthChooseVos = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
                for (MonthChooseVo monthChooseVo : monthChooseVos) {
                    ElectricityLevelEntity electricityLevel = new ElectricityLevelEntity();
                    electricityLevel.setOneParamName(oneType);
                    electricityLevel.setLevelParamDesc(monthChooseVo.getParamDesc());
                    electricityLevel.setLevelParamName(monthChooseVo.getParamName());
                    electricityLevelEntities.add(electricityLevel);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityLevel();
            return electricityLevelService.saveOrUpdateBatch(electricityLevelEntities);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMonthChooseElectricity() {
        List<ElectricityTypeOneEntity> list = electricityTypeIService.list();
        if (list != null && list.size() > 0) {
            ElectricityPriceDto dto = new ElectricityPriceDto();
            List<ElectricityMonthChooseAnalysisEntity> electricityLevelEntities = new ArrayList<>();
            for (ElectricityTypeOneEntity electricityTypeOne : list) {

                dto.setElectricityTypeOneName(electricityTypeOne.getOneParamName());
                dto.setRegionName(electricityTypeOne.getRegionName());

                JSONObject monthChooseElectricityData = getMonthChooseElectricityData(dto);
                // 判断响应码是否正确
                if (!Integer.valueOf(0).equals(monthChooseElectricityData.getInteger("resp_code"))) {
                    log.info("采集数据失败-月份选择(电价分析): {}", monthChooseElectricityData.toJSONString());
                    return false;
                }

                // 获取数据列表
                JSONArray dataList = monthChooseElectricityData.getJSONArray("datas");
                if (dataList == null || dataList.isEmpty()) {
                    log.info("采集数据为空-月份选择(电价分析)");
                    return false;
                }
                List<MonthChooseVo> monthChooseVos = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
                for (MonthChooseVo monthChooseVo : monthChooseVos) {
                    ElectricityMonthChooseAnalysisEntity electricityLevel = new ElectricityMonthChooseAnalysisEntity();
                    electricityLevel.setRegionName(electricityTypeOne.getRegionName());
                    electricityLevel.setOneParamName(electricityTypeOne.getOneParamName());
                    electricityLevel.setMonthParamDesc(monthChooseVo.getParamDesc());
                    electricityLevel.setMonthParamName(monthChooseVo.getParamName());
                    electricityLevelEntities.add(electricityLevel);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            // 全量更新：先删除旧数据，再批量保存新数据
            electricityTypeIMapper.deleteAllElectricityMonthChooseAnalysis();
            return electricityMonthChooseAnalysisService.saveOrUpdateBatch(electricityLevelEntities);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePeakValleySpread() {
        JSONObject peakValleySpreadData = getPeakValleySpreadData();
        // 判断响应码是否正确
        if (!Integer.valueOf(0).equals(peakValleySpreadData.getInteger("resp_code"))) {
            log.info("采集数据失败-月份选择(电价分析): {}", peakValleySpreadData.toJSONString());
            return false;
        }

        // 获取数据列表
        JSONArray dataList = peakValleySpreadData.getJSONArray("datas");
        if (dataList == null || dataList.isEmpty()) {
            log.info("采集数据为空-月份选择(电价分析)");
            return false;
        }
        List<MonthChooseVo> monthChooseVos = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
        List<ElectricityPeakValleySpreadEntity> valleySpreadEntities = new ArrayList<>();
        for (MonthChooseVo monthChooseVo : monthChooseVos) {
            ElectricityPeakValleySpreadEntity spreadEntity = new ElectricityPeakValleySpreadEntity();
            spreadEntity.setPeakValleySpreadParamDesc(monthChooseVo.getParamDesc());
            spreadEntity.setPeakValleySpreadParamName(monthChooseVo.getParamName());
            valleySpreadEntities.add(spreadEntity);
        }
        // 全量更新：先删除旧数据，再批量保存新数据
        electricityTypeIMapper.deleteAllElectricityPeakValleySpread();

        return electricityPeakValleySpreadService.saveOrUpdateBatch(valleySpreadEntities);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateElectricityPriceAnalysis() {
        LambdaQueryWrapper<ElectricityMonthChooseAnalysisEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ElectricityMonthChooseAnalysisEntity::getRegionName, "全国");
        List<ElectricityMonthChooseAnalysisEntity> monthEntities = electricityMonthChooseAnalysisService.list(wrapper);
        if (monthEntities != null && monthEntities.size() > 0) {
            List<ElectricityLevelEntity> levelEntities = electricityLevelService.list();
            Map<String, List<ElectricityLevelEntity>> listMap = levelEntities.stream().collect(Collectors.groupingBy(ElectricityLevelEntity::getOneParamName));
            if (levelEntities != null && levelEntities.size() > 0) {
                List<ElectricityPeakValleySpreadEntity> spreadEntities = electricityPeakValleySpreadService.list();
                if (spreadEntities != null && spreadEntities.size() > 0) {
                    ElectricityPriceDto dto = new ElectricityPriceDto();
                    List<ElectricityPriceAnalysisEntity> electricityPriceAnalysisEntities = new ArrayList<>();
                    for (ElectricityMonthChooseAnalysisEntity monthEntity : monthEntities) {
                        List<ElectricityLevelEntity> electricityLevelEntities = listMap.get(monthEntity.getOneParamName());
                        for (ElectricityLevelEntity electricityLevelEntity : electricityLevelEntities) {
                            for (ElectricityPeakValleySpreadEntity spreadEntity : spreadEntities) {
                                List<String> arrayList = new ArrayList<>();
                                arrayList.add(monthEntity.getRegionName());
                                dto.setElectricityTypeOneName(monthEntity.getOneParamName());
                                dto.setRegionNameList(arrayList);
                                dto.setYears(monthEntity.getMonthParamName());
                                dto.setTariffLevelId(electricityLevelEntity.getLevelParamName());
                                dto.setDifferencePrice(spreadEntity.getPeakValleySpreadParamName());
                                JSONObject electricityPriceAnalysisData = getElectricityPriceAnalysisData(dto);
                                // 判断响应码是否正确
                                if (!Integer.valueOf(0).equals(electricityPriceAnalysisData.getInteger("resp_code"))) {
                                    log.info("采集数据失败-月份选择(电价分析): {}", electricityPriceAnalysisData.toJSONString());
                                    return false;
                                }

                                // 获取数据列表
                                JSONArray dataList = electricityPriceAnalysisData.getJSONArray("datas");
                                if (dataList == null || dataList.isEmpty()) {
                                    log.info("采集数据为空-月份选择(电价分析)");
                                    return false;
                                }
                                List<AnalysisVo> analysisVoList = JSON.parseArray(JSON.toJSONString(dataList), AnalysisVo.class);
                                for (AnalysisVo analysisVo : analysisVoList) {
                                    ElectricityPriceAnalysisEntity electricityPriceAnalysisEntity = new ElectricityPriceAnalysisEntity();
                                    electricityPriceAnalysisEntity.setMonthParamName(dto.getYears());
                                    electricityPriceAnalysisEntity.setLevelParamName(dto.getTariffLevelId());
                                    electricityPriceAnalysisEntity.setPeakValleySpreadParamName(dto.getDifferencePrice());
                                    electricityPriceAnalysisEntity.setOneParamName(dto.getElectricityTypeOneName());

                                    electricityPriceAnalysisEntity.setRegionName(analysisVo.getRegionName());
                                    electricityPriceAnalysisEntity.setElectrovalenceDifference(analysisVo.getElectrovalenceDifference());
                                    electricityPriceAnalysisEntity.setSameRatio(analysisVo.getSameRatio());
                                    electricityPriceAnalysisEntity.setRingRatio(analysisVo.getRingRatio());
                                    electricityPriceAnalysisEntities.add(electricityPriceAnalysisEntity);
                                }
//                                try {
//                                    Thread.sleep(200);
//                                } catch (InterruptedException e) {
//                                    Thread.currentThread().interrupt();
//                                }
                            }
                        }

                    }
                    // 全量更新：先删除旧数据，再批量保存新数据
                    electricityTypeIMapper.deleteAllElectricityPriceAnalysis();
                    return electricityPriceAnalysisService.saveOrUpdateBatch(electricityPriceAnalysisEntities);
                }
            }
        }


        return false;
    }

    public List<RegionVo> getRegionAndElectricityTypeIStatic(ElectricityPriceDto electricityPriceDto) {
        String type = electricityPriceDto.getType();
        List<ElectricityTypeOneEntity> list = electricityTypeIService.list();

        if (list == null || list.isEmpty()) {
            return Collections.emptyList();
        }

        // 按区域分组
        Map<String, List<ElectricityTypeOneEntity>> regionNameMap =
                list.stream().collect(Collectors.groupingBy(ElectricityTypeOneEntity::getRegionName));

        return regionNameMap.entrySet().stream()
                .filter(entry -> "all".equals(type) || !entry.getKey().equals("全国"))
                .map(entry -> createRegionVo(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
    }

    /**
     * 创建 RegionVo 对象
     */
    private RegionVo createRegionVo(String regionName, List<ElectricityTypeOneEntity> entities) {
        List<RegionVo.ReInvestmentElectricityType> reInvestmentElectricityTypes = entities.stream()
                .map(this::createReInvestmentElectricityType)
                .collect(Collectors.toList());

        RegionVo regionVo = new RegionVo();
        regionVo.setRegionName(regionName);
        regionVo.setReInvestmentElectricityType(reInvestmentElectricityTypes);
        return regionVo;
    }

    /**
     * 创建 ReInvestmentElectricityType 对象
     */
    private RegionVo.ReInvestmentElectricityType createReInvestmentElectricityType(ElectricityTypeOneEntity entity) {
        RegionVo.ReInvestmentElectricityType reInvestmentElectricityType = new RegionVo.ReInvestmentElectricityType();
        reInvestmentElectricityType.setParamDesc(entity.getOneParamDesc());
        reInvestmentElectricityType.setParamName(entity.getOneParamName());
        return reInvestmentElectricityType;
    }

    @Override
    public List<VoltageVo> getVoltageAndElectricityTypeII(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getRegionName()) || "全国".equals(electricityPriceDto.getRegionName())) {
            throw new RuntimeException("区域名称参数错误");
        }
        List<VoltageVo> voltageVoList = new ArrayList<>();
        JSONObject jsonObject = getVoltageAndElectricityTypeIIData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                voltageVoList = JSON.parseArray(JSON.toJSONString(dataList), VoltageVo.class);
            }
        } else {
            log.info("获取用电类型II电压等级数据失败" + jsonObject.toJSONString());
            LambdaQueryWrapper<ElectricityTypeTwoVoltageEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ElectricityTypeTwoVoltageEntity::getOneParamName, electricityPriceDto.getElectricityTypeOneName());
            wrapper.eq(ElectricityTypeTwoVoltageEntity::getRegionName, electricityPriceDto.getRegionName());
            List<ElectricityTypeTwoVoltageEntity> list = electricityTypeTwoVoltageService.list(wrapper);
            Map<String, List<ElectricityTypeTwoVoltageEntity>> electricityTypeTwoVoltageMap = list.stream().collect(Collectors.groupingBy(ElectricityTypeTwoVoltageEntity::getTwoParamName));
            for (Map.Entry<String, List<ElectricityTypeTwoVoltageEntity>> electricityTypeTwoVoltage : electricityTypeTwoVoltageMap.entrySet()) {
                VoltageVo voltageVo = new VoltageVo();
                ArrayList<VoltageVo.VoltageLevel> voltageLevels = new ArrayList<>();
                for (ElectricityTypeTwoVoltageEntity twoVoltageEntity : electricityTypeTwoVoltage.getValue()) {
                    voltageVo.setParamName(twoVoltageEntity.getTwoParamName());
                    voltageVo.setParamDesc(twoVoltageEntity.getTwoParamDesc());
                    VoltageVo.VoltageLevel voltageLevel = new VoltageVo.VoltageLevel();
                    voltageLevel.setParamDesc(twoVoltageEntity.getVoltageParamDesc());
                    voltageLevel.setParamName(twoVoltageEntity.getVoltageParamName());
                    voltageLevels.add(voltageLevel);
                    voltageVo.setVoltageLevel(voltageLevels);
                }
                voltageVoList.add(voltageVo);
            }
        }
        return voltageVoList;
    }

    @Override
    public List<DivideHourVo> getTest(ElectricityPriceDto electricityPriceDto) {
        List<DivideHourVo> divideHourVos = new ArrayList<>();
        LambdaQueryWrapper<ElectricityDivideHourEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ElectricityDivideHourEntity::getRegionName, electricityPriceDto.getRegionName());
        wrapper.eq(ElectricityDivideHourEntity::getOneParamName, electricityPriceDto.getElectricityTypeOneName());
        wrapper.eq(ElectricityDivideHourEntity::getTwoParamName, electricityPriceDto.getElectricityTypeTwoName());
        wrapper.eq(ElectricityDivideHourEntity::getVoltageParamName, electricityPriceDto.getTariffLevelId());
        wrapper.eq(ElectricityDivideHourEntity::getMonthParamName, electricityPriceDto.getYears());
        List<ElectricityDivideHourEntity> list = electricityDivideHourService.list(wrapper);
        if (list != null && list.size() > 0) {
            for (ElectricityDivideHourEntity electricityDivideHour : list) {
                DivideHourVo divideHourVo = new DivideHourVo();
                divideHourVo.setElectrovalence(electricityDivideHour.getElectrovalence());
                divideHourVo.setPeriodType(electricityDivideHour.getPeriodType());
                divideHourVo.setStartTime(electricityDivideHour.getStartTime());
                divideHourVo.setEndTime(electricityDivideHour.getEndTime());
                divideHourVos.add(divideHourVo);
            }
        }
        return divideHourVos;
    }

    public JSONObject getVoltageAndElectricityTypeIIData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        //请求第三方接口
        String url = String.format("%s?electricityTypeOneName=%s&regionName=%s", Constant.YDLXII_DYDJ
                , electricityPriceDto.getElectricityTypeOneName(), electricityPriceDto.getRegionName());
        Object dataObject = templateService.get(url, headerMap, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<MonthChooseVo> getMonthChoose(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getRegionName()) || "全国".equals(electricityPriceDto.getRegionName())) {
            throw new RuntimeException("区域名称参数错误");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeTwoName())) {
            throw new RuntimeException("用电类型II不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getTariffLevelId())) {
            throw new RuntimeException("电压等级不能为空");
        }

        List<MonthChooseVo> chooseArrayList = new ArrayList<>();
        JSONObject jsonObject = getMonthChooseData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                chooseArrayList = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
            }
        } else {
            //展示库中数据
            LambdaQueryWrapper<ElectricityMonthChooseEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ElectricityMonthChooseEntity::getRegionName, electricityPriceDto.getRegionName());
            wrapper.eq(ElectricityMonthChooseEntity::getOneParamName, electricityPriceDto.getElectricityTypeOneName());
            wrapper.eq(ElectricityMonthChooseEntity::getTwoParamName, electricityPriceDto.getElectricityTypeTwoName());
            wrapper.eq(ElectricityMonthChooseEntity::getVoltageParamName, electricityPriceDto.getTariffLevelId());
            List<ElectricityMonthChooseEntity> list = electricityMonthChooseService.list(wrapper);
            if (list != null && list.size() > 0) {
                for (ElectricityMonthChooseEntity electricityMonthChooseEntity : list) {
                    MonthChooseVo monthChooseVo = new MonthChooseVo();
                    monthChooseVo.setParamName(electricityMonthChooseEntity.getMonthParamName());
                    monthChooseVo.setParamDesc(electricityMonthChooseEntity.getMonthParamDesc());
                    chooseArrayList.add(monthChooseVo);
                }
            }

        }
        return chooseArrayList;
    }

    public JSONObject getMonthChooseData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        body.put("regionName", electricityPriceDto.getRegionName());
        body.put("electricityTypeOneName", electricityPriceDto.getElectricityTypeOneName());
        body.put("electricityTypeTwoName", electricityPriceDto.getElectricityTypeTwoName());
        body.put("tariffLevelId", electricityPriceDto.getTariffLevelId());
        Object dataObject = templateService.postByModelExchange(Constant.YFXZ, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<DivideHourVo> getDivideHourElectricity(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getRegionName()) || "全国".equals(electricityPriceDto.getRegionName())) {
            throw new RuntimeException("区域名称参数错误");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeTwoName())) {
            throw new RuntimeException("用电类型II不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getTariffLevelId())) {
            throw new RuntimeException("电压等级不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getYears())) {
            throw new RuntimeException("年份不能为空");
        }
        List<DivideHourVo> divideHourElectricityVoList = new ArrayList<>();
        JSONObject jsonObject = getDivideHourElectricityData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                divideHourElectricityVoList = JSON.parseArray(JSON.toJSONString(dataList), DivideHourVo.class);
            }
        } else {
            //展示库中数据

        }

        return divideHourElectricityVoList;
    }

    public JSONObject getDivideHourElectricityData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        body.put("regionName", electricityPriceDto.getRegionName());
        body.put("electricityTypeOneName", electricityPriceDto.getElectricityTypeOneName());
        body.put("electricityTypeTwoName", electricityPriceDto.getElectricityTypeTwoName());
        body.put("tariffLevelId", electricityPriceDto.getTariffLevelId());
        body.put("years", electricityPriceDto.getYears());
        Object dataObject = templateService.postByModelExchange(Constant.FSDJ, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<DivideMonthVo> getDivideMonthElectricity(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getRegionName()) || "全国".equals(electricityPriceDto.getRegionName())) {
            throw new RuntimeException("区域名称参数错误");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeTwoName())) {
            throw new RuntimeException("用电类型II不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getTariffLevelId())) {
            throw new RuntimeException("电压等级不能为空");
        }
        List<DivideMonthVo> divideMonthVoList = new ArrayList<>();
        JSONObject jsonObject = getDivideMonthElectricityData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                divideMonthVoList = JSON.parseArray(JSON.toJSONString(dataList), DivideMonthVo.class);
            }
        } else {
            //展示库中数据

        }

        return divideMonthVoList;
    }

    public JSONObject getDivideMonthElectricityData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        body.put("regionName", electricityPriceDto.getRegionName());
        body.put("electricityTypeOneName", electricityPriceDto.getElectricityTypeOneName());
        body.put("electricityTypeTwoName", electricityPriceDto.getElectricityTypeTwoName());
        body.put("tariffLevelId", electricityPriceDto.getTariffLevelId());
        Object dataObject = templateService.postByModelExchange(Constant.FYDJ, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<PeakValleyVo> getPeakValleyPriceDifference(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getRegionName()) || "全国".equals(electricityPriceDto.getRegionName())) {
            throw new RuntimeException("区域名称参数错误");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeTwoName())) {
            throw new RuntimeException("用电类型II不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getTariffLevelId())) {
            throw new RuntimeException("电压等级不能为空");
        }
        List<PeakValleyVo> peakValleyList = new ArrayList<>();
        JSONObject jsonObject = getPeakValleyPriceDifferenceData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                peakValleyList = JSON.parseArray(JSON.toJSONString(dataList), PeakValleyVo.class);
            }
        } else {
            //展示库中数据

        }
        return peakValleyList;
    }

    public JSONObject getPeakValleyPriceDifferenceData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        body.put("regionName", electricityPriceDto.getRegionName());
        body.put("electricityTypeOneName", electricityPriceDto.getElectricityTypeOneName());
        body.put("electricityTypeTwoName", electricityPriceDto.getElectricityTypeTwoName());
        body.put("tariffLevelId", electricityPriceDto.getTariffLevelId());
        Object dataObject = templateService.postByModelExchange(Constant.FGCJ, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }

    }

    @Override
    public List<AnalysisVo> getElectricityPriceAnalysis(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (ObjectUtils.isNull(electricityPriceDto.getRegionNameList())) {
            throw new RuntimeException("区域名称列表不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getDifferencePrice())) {
            throw new RuntimeException("峰谷价差不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getTariffLevelId())) {
            throw new RuntimeException("电压等级不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getYears())) {
            throw new RuntimeException("年份不能为空");
        }
        List<AnalysisVo> analysisList = new ArrayList<>();
        JSONObject jsonObject = getElectricityPriceAnalysisData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                analysisList = JSON.parseArray(JSON.toJSONString(dataList), AnalysisVo.class);
            }
        } else {
            //展示库中数据
        }

        return analysisList;
    }

    public JSONObject getElectricityPriceAnalysisData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        body.put("regionName", electricityPriceDto.getRegionNameList());
        body.put("electricityTypeOneName", electricityPriceDto.getElectricityTypeOneName());
        body.put("tariffLevelId", electricityPriceDto.getTariffLevelId());
        body.put("years", electricityPriceDto.getYears());
        body.put("differencePrice", electricityPriceDto.getDifferencePrice());
        Object dataObject = templateService.postByModelExchange(Constant.DJFX, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<MonthChooseVo> getElectricityLevel(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        List<MonthChooseVo> electricityLevelList = new ArrayList<>();
        JSONObject jsonObject = getElectricityLevelData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                electricityLevelList = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
            }
        } else {
            //展示库中数据

        }

        return electricityLevelList;
    }

    public JSONObject getElectricityLevelData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        String url = String.format("%s?electricityTypeOne=%s", Constant.DYDJ
                , electricityPriceDto.getElectricityTypeOneName());
        Object dataObject = templateService.postByModelExchange(url, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<MonthChooseVo> getMonthChooseElectricity(ElectricityPriceDto electricityPriceDto) {
        if (electricityPriceDto == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getElectricityTypeOneName())) {
            throw new RuntimeException("用电类型I不能为空");
        }
        if (StringUtils.isEmpty(electricityPriceDto.getRegionName())) {
            throw new RuntimeException("区域名称不能为空");
        }
        List<MonthChooseVo> electricityLevelList = new ArrayList<>();
        JSONObject jsonObject = getMonthChooseElectricityData(electricityPriceDto);
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                electricityLevelList = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
            }
        } else {
            // 展示库中数据
        }

        return electricityLevelList;
    }

    public JSONObject getMonthChooseElectricityData(ElectricityPriceDto electricityPriceDto) {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        String url = String.format("%s?electricityTypeOneName=%s&regionName=%s", Constant.DJFX_YFXZ
                , electricityPriceDto.getElectricityTypeOneName(), electricityPriceDto.getRegionName());
        Object dataObject = templateService.postByModelExchange(url, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }

    @Override
    public List<MonthChooseVo> getPeakValleySpread() {
        List<MonthChooseVo> electricityLevelList = new ArrayList<>();
        JSONObject jsonObject = getPeakValleySpreadData();
        if (jsonObject.getInteger("resp_code").equals(0)) {
            JSONArray dataList = jsonObject.getJSONArray("datas");
            if (dataList != null && dataList.size() > 0) {
                electricityLevelList = JSON.parseArray(JSON.toJSONString(dataList), MonthChooseVo.class);
            }
        } else {
            // 展示库中数据
        }
        return electricityLevelList;
    }

    public JSONObject getPeakValleySpreadData() {
        Map<String, String> headerMap = getHeaderMap();
        JSONObject body = new JSONObject();
        Object dataObject = templateService.postByModelExchange(Constant.DJFX_FGCJ, headerMap, body, Object.class);
        if (dataObject != null) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(dataObject));
            if (!jsonObject.getInteger("resp_code").equals(0)) {
                log.info("获取第三方数据失败：" + jsonObject.toJSONString());
            }
            return jsonObject;
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("resp_code", 1);
            return jsonObject;
        }
    }


    public Map<String, String> getHeaderMap() {
        String nonce = SignUtils.generateRandomNumber(10, 50);
        long timestamp = System.currentTimeMillis();
        String signData = SignUtils.getSignData(appId, appSecret, timestamp, nonce);
        //请求头
        Map<String, String> headerMap = InitHashMapUtil.InitHashMap();
        headerMap.put("appId", appId);
        headerMap.put("timestamp", String.valueOf(timestamp));
        headerMap.put("sign", signData);
        headerMap.put("nonce", nonce);
        return headerMap;
    }

    @Override
    @Transactional
    public boolean updateElectricityPriceByCId(ElectricityPriceByCIdDto electricityPriceByCIdDto) {
        String cid = electricityPriceByCIdDto.getCid();
        LambdaQueryWrapper<ElectricityPriceCidEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ElectricityPriceCidEntity::getCId, cid);
        wrapper.eq(ElectricityPriceCidEntity::getYear, electricityPriceByCIdDto.getYear());
        List<ElectricityPriceCidEntity> list = electricityPriceCidService.list(wrapper);
        if (list != null || list.size() > 0) {
            electricityPriceCidService.remove(wrapper);
        }
        if (electricityPriceByCIdDto.getDivideHourData() != null
                && electricityPriceByCIdDto.getDivideHourData().size() > 0) {
            List<DivideHourVo> divideHourData = electricityPriceByCIdDto.getDivideHourData();
            List<ElectricityPriceCidEntity> electricityPriceCidEntities = new ArrayList<>();
            for (DivideHourVo divideHourDatum : divideHourData) {
                ElectricityPriceCidEntity electricityPriceCidEntity = new ElectricityPriceCidEntity();
                electricityPriceCidEntity.setCId(cid);
                electricityPriceCidEntity.setStartTime(divideHourDatum.getStartTime());
                electricityPriceCidEntity.setEndTime(divideHourDatum.getEndTime());
                electricityPriceCidEntity.setPeriodType(divideHourDatum.getPeriodType());
                electricityPriceCidEntity.setElectrovalence(divideHourDatum.getElectrovalence());
                electricityPriceCidEntity.setYear(electricityPriceByCIdDto.getYear());
                electricityPriceCidEntities.add(electricityPriceCidEntity);
            }
            return electricityPriceCidService.saveOrUpdateBatch(electricityPriceCidEntities);
        }
        return false;
    }

    @Override
    public List<DivideHourVo> getElectricityPriceByCId(ElectricityPriceByCIdDto electricityPriceByCIdDto) {
        String cid = electricityPriceByCIdDto.getCid();
        LambdaQueryWrapper<ElectricityPriceCidEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ElectricityPriceCidEntity::getCId, cid);
        wrapper.eq(ElectricityPriceCidEntity::getYear, electricityPriceByCIdDto.getYear());
        List<ElectricityPriceCidEntity> list = electricityPriceCidService.list(wrapper);
        List<DivideHourVo> divideHourVos = new ArrayList<>();
        if (list != null || list.size() > 0) {
            for (ElectricityPriceCidEntity electricityPriceCidEntity : list) {
                DivideHourVo divideHourVo = new DivideHourVo();
                divideHourVo.setElectrovalence(electricityPriceCidEntity.getElectrovalence());
                divideHourVo.setPeriodType(electricityPriceCidEntity.getPeriodType());
                divideHourVo.setStartTime(electricityPriceCidEntity.getStartTime());
                divideHourVo.setEndTime(electricityPriceCidEntity.getEndTime());
                divideHourVos.add(divideHourVo);
            }
            return divideHourVos;
        }
        return divideHourVos;
    }


}
